﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Ecopsy.Tools;
using AgencyEntityLib.BaseEntity;
using FormControllers;
using SqlLibrary;
using Ecopsy.DataTier;

public partial class Ctl_ctlTaskList : System.Web.UI.UserControl
{
    wsTask ws_Task = (wsTask)GlobalConstants.CurrentAgency.WS_FactoryList[WS_FactoryList.wsKey_Task];
    
    

    protected void Page_Load(object sender, EventArgs e)
    {
        InitControl();
    }
    #region Свойства

    public DateTime StartDate { get { return ((TaskList.sqlLoadStatment)Where.ListLoadStatment).dtStart; }
        set { ((TaskList.sqlLoadStatment)Where.ListLoadStatment).dtStart = value; } }
    public DateTime EndDate { get { return ((TaskList.sqlLoadStatment)Where.ListLoadStatment).dtFinish ; } 
        set { ((TaskList.sqlLoadStatment)Where.ListLoadStatment).dtFinish = value; } }
    

    /// <summary>
    /// Строка поиска
    /// </summary>
    public string Lexeme {get {return Where.ListLoadStatment.Lexeme; } set{Where.ListLoadStatment.Lexeme=value ;}}

    /// <summary>
    /// ID типа задачи
    /// </summary>
    public string CategoriaID {get{ return  ((TaskList.sqlLoadStatment) Where.ListLoadStatment).CtegoriaID ;} 
        set
        {
            if(string.IsNullOrEmpty (value ))
                ((TaskList.sqlLoadStatment) Where.ListLoadStatment).CtegoriaID= string.Empty;
            else 
                ((TaskList.sqlLoadStatment) Where.ListLoadStatment).CtegoriaID= value ;}
        }

    /// <summary>
    /// Дата начал периода
    /// </summary>
    public DateTime  dtStart
    {
        get { return ((TaskList.sqlLoadStatment)Where.ListLoadStatment).dtStart ; }
        set
        {            
                ((TaskList.sqlLoadStatment)Where.ListLoadStatment).dtStart = value;
        }
    }

    /// <summary>
    /// Дата окончания периода
    /// </summary>
    public DateTime dtFinish
    {
        get { return ((TaskList.sqlLoadStatment)Where.ListLoadStatment).dtFinish; }
        set
        {
            ((TaskList.sqlLoadStatment)Where.ListLoadStatment).dtFinish = value;
        }
    }


    /// <summary>
    /// ключ кэша 
    /// </summary>
    private string _key = "TaskList";
    public string Key { get {return _key ; } set {_key =value ; } }
    #endregion

    protected override void OnDataBinding(EventArgs e)
    {
        base.OnDataBinding(e);
        MyBind();
    }

    private void InitControl()
    {
        //привязать событие открыть закрыть lvTask
        if (lvTask.EditItem != null)
        {
            Ctl_ctlTaskEditor r = (Ctl_ctlTaskEditor)lvTask.EditItem.FindControl("ctlTaskEditor1");
            r.OnCancelClick = OnTaskEditorClick;
            r.OnMyDataChanged = OnTaskEditorDataChanged;
        }
    }
    
    private void MyBind()
    {
        ObjectDS_PF ODS = new ObjectDS_PF(GetLvList);
        lvTask.DataSource = ODS.ImAsObjectDataSource;
        lvTask.DataBind () ;
        pnlHead.DataBind();
    }

    protected void lvSort(object sender, EventArgs e)
    {
        lvTask.EditIndex = -1;
        string s = ((LinkButton)sender).CommandArgument;
        Where.SortCondition.SortDirection = (Where.SortCondition.SortDirection == SortDirection.Ascending ? SortDirection.Descending : SortDirection.Ascending); ;
        Where.SortCondition.SortField = s;
        MyBind();
    }

    
    protected grdTask[] GetLvList(int startRowIndex, int maximumRows, out int RowCount)
    {                
        Task[] l =  GetList(Where, out RowCount, startRowIndex, maximumRows);
        
        grdTask[] res = TaskExt.ToGrdTask(l);
        //заряжаем comparer функцией сортировки 
        Where.SortCondition.fnOrderBy = SortFunctions.fOrderBy;
        // Сортируем
        Array.Sort(res, Where.SortCondition);
        return res;

    }

    protected void ReverceTaskState(object sender, EventArgs e)
    {
        string s = ((Button)sender).CommandArgument;
        wsTask ws = (wsTask)GlobalConstants.CurrentAgency.WS_FactoryList[WS_FactoryList.wsKey_Task];
        
        Task t = ws.GetTask(s);
        t.IsClosed = !t.IsClosed;
        ws.SaveTask(t);
        MyBind();

    }

    protected string GetHeadCss(string HearTd)
    {
        if (Where.SortCondition.SortField != HearTd) return string.Empty;
        return "sort" + Where.SortCondition.SortDirection.ToString();
    }

    /// <summary>
    /// фильтр формы - сохраняемый в кэше
    /// </summary>
    public  ListWhere Where
    {
        get
        {
            ListWhere r = null;
            if (!CacheTools.IsSessionCacheObject (Key ))
            {
                r = new ListWhere();
                r.ListLoadStatment = new TaskList.sqlLoadStatment();
                r.SortCondition.SortDirection = SortDirection.Ascending;
                r.SortCondition.SortField = "s_TaskContent";
                CacheTools.SetSessionCacheObject (Key, r);
            }
            return (ListWhere)CacheTools.GetSessionCacheObect (Key);
        }
        set
        {
            CacheTools.ResetSessionCache(Key);
            CacheTools.SetSessionCacheObject(Key, value);
        }

    }

    TaskList l= null;
    public Task[] GetList(
                                           object _Where,
                                           out int RowCount,
                                           int startRowIndex,
                                           int endRowIndex
                                       )
    {

        ListWhere w = (ListWhere)_Where;
        w.ListLoadStatment.StartRowIndex = startRowIndex;
        w.ListLoadStatment.EndRowIndex = endRowIndex; 
        
        if(null==l) 
            l = ws_Task.GetTaskList((TaskList.sqlLoadStatment)w.ListLoadStatment);

        RowCount = l.OutputRwCnt;
        return l.ToList<Task>().ToArray<Task>();
    }


    

    protected void ItemCommand(object sender, ListViewCommandEventArgs e)
    {
        if (string.Empty == e.CommandName) return;

        ListView lv = (ListView)sender;



        switch (e.CommandName)
        {
            case "Edit":
                {

                    ListViewDataItem d = (ListViewDataItem)e.Item;
                    lv.EditIndex = d.DataItemIndex;

                    break;
                }
            case "Insert":
                {

                    break;
                }
            case "Update":
                {
                    //if (LvUpdCmd((ListViewDataItem)e.Item)) lv.EditIndex = -1;
                    //SetMsg_EditStatus();
                    break;
                }
            case "Delete":
                {
                    //DeleteCustomer(e.CommandArgument as string);
                    break;
                }
        }

        //switch (lv.ID)    
        MyBind();


    }
    protected void ItemEditing(object sender, ListViewEditEventArgs e)
    {

    }
    protected void ItemUpdating(object sender, ListViewUpdateEventArgs e)
    {

    }
    protected void lvTask_SelectedIndexChanged(object sender, EventArgs e)
    {

    }
    protected void lvTask_PagePropertiesChanged(object sender, EventArgs e)
    {
        MyBind();
    }
    protected void lvTask_ItemCommand(object sender, ListViewCommandEventArgs e)
    {

    }

    protected bool OnTaskEditorClick()
    {
        lvTask.EditIndex = -1;
        MyBind();
        return true;
    }
    protected bool OnTaskEditorDataChanged()
    {
        MyBind();
        return true;
    }

    public string GetRowCSS(string s)
    {
        return s;
    }

    protected string Get_OnMouseover(string s_Closed)
    {
        if (s_Closed.IndexOf("Просроченна") == -1) return "GrdItemOnMouseOver(this);";
        return ";";
                
    }

    

}
